html-loader
作用:
将html导出为字符串。
API:https://github.com/webpack-contrib/html-loader
安装:
npm install html-loader --save-dev
使用:
一、基本用法
import html from "html-loader?./html/test.html";
此时变量html
就是一个单纯的html字符串,如果test.html
包含url等地址,也是原样输出。
二、字符串属性值处理
<!--test.html-->
<div>
<img src="../images/bg.jpg" />
</div>
//webpack.config.js
rules:[
{
test:/\.jpg$/,
include:/src/,
use:[
{
loader:'file-loader',
options:{
name:"[name].[ext]",
outputPath:"img/"
}
}
]
}
]
此时,我们为html-loader指定参数:
import html from 'html-loader?attrs=img:src!./html/test.html';
/*
<div>
<img src="img/bg.jpg" />
</div>
*/
//img标签下的src属性值被处理
指定多个参数:
import html from 'html-loader?attrs=img:src img:data-src!./html/test.html';
//等价于
import html from 'html-loader?attrs[]=img:src&attrs[]=img:data-src!./html/test.html';
//img标签下的src属性和data-src属性值被处理
缺省标签:
import html from 'html-loader?attrs=:src :data-src!./html/test.html';
//等价于
import html from 'html-loader?attrs[]=:src&attrs[]=:data-src!./html/test/html';
//所有标签下的src属性和data-src属性被处理
三、最小化
rules:[
{
test:/\.html$/,
use:[
{
loader:'html-loader',
options:{
minimize:true
}
}
]
}
]
这样,html便会被压缩。具体压缩参数有很多,可以参考顶部链接。
四、webpack.config.js配置
rules:[
{
test:/\.html$/,
use:[
{
loader:'html-loader',
options:{
attrs:['img:src',':data-src']
}
}
]
}
]
文档中指定config参数的方式,实际测试会报错,要注意。
五、ES6插值
let html = `${require("./html/demo1.html")}`
六、导出html文件
结合之前的file-loader、extract-loader、html-loader,导出html文件。而不是通过js来插入:
rules:[
{
test:/\.html$/,
use:[
{
loader:'file-loader',
options:{
name:'[name].[ext]',
outputPath:'html/'
}
},
{
loader:'extract-loader',
options:{
publicpath:'../'
}
},
{
loader:'html-loader',
options:{
minimize:true,
}
}
]
}
]
总结:
html-loader就是模板字符串化,应用场景。。。。